import 'package:easy_chat_app/commons/GlobalStatus.dart';
import 'package:easy_chat_app/commons/model/Result.dart';
import 'package:easy_chat_app/commons/utils/RouteUtils.dart';
import 'package:easy_chat_app/commons/utils/StringUtils.dart';
import 'package:easy_chat_app/commons/utils/TokenUtils.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:logger/logger.dart';
import 'package:provider/provider.dart';

class MobileLoginPage extends StatefulWidget {
  const MobileLoginPage({super.key});

  @override
  State<StatefulWidget> createState() {
    return _MobileLoginPage();
  }
}

class _MobileLoginPage extends State<MobileLoginPage> {
  Logger logger = Logger();

  FocusNode accountFocusNode = FocusNode();
  FocusNode passwordFocusNode = FocusNode();

  TextEditingController accountTextEditingController = TextEditingController();
  TextEditingController passwordTextEditingController = TextEditingController();

  String warningMsg = "";

  bool accountErrStatus = false;
  bool passwordErrStatus = false;

  @override
  void initState() {
    super.initState();
    accountTextEditingController.text = "17600196389";
    passwordTextEditingController.text = "111111";
  }

  @override
  void dispose() {
    super.dispose();
    accountTextEditingController.dispose();
    passwordTextEditingController.dispose();
  }

  void setWarningMsg(String msg, bool accountErrStatus, passwordErrStatus) {
    warningMsg = msg;
    this.accountErrStatus = accountErrStatus;
    this.passwordErrStatus = passwordErrStatus;
    setState(() {});
  }

  @override
  Widget build(BuildContext context) {
    accountFocusNode.addListener(() {
      if (accountFocusNode.hasFocus) {
        accountErrStatus = false;
        setState(() {});
      }
    });

    passwordFocusNode.addListener(() {
      if (passwordFocusNode.hasFocus) {
        passwordErrStatus = false;
        setState(() {});
      }
    });

    return Consumer<AppUserDetailChangeNotifier>(
        builder: (context, appUserDetailChangeNotifier, child) {
      return Scaffold(
          body: Container(
        height: double.infinity,
        color: Colors.white,
        child: SingleChildScrollView(
          padding: const EdgeInsets.only(top: 100, left: 20, right: 20),
          child: Column(
            children: [
              const FlutterLogo(
                size: 100,
              ),
              const SizedBox(
                width: double.infinity,
                height: 20,
              ),
              CupertinoApp(
                debugShowCheckedModeBanner: false,
                home: Container(
                  color: Colors.white,
                  child: Container(
                    padding: const EdgeInsets.all(5),
                    decoration: BoxDecoration(
                        border: accountErrStatus
                            ? const Border.fromBorderSide(
                                BorderSide(color: Colors.red))
                            : null,
                        color: const Color.fromRGBO(249, 249, 250, 1),
                        borderRadius:
                            const BorderRadius.all(Radius.circular(10))),
                    child: CupertinoTextField(
                      maxLength: 30,
                      placeholder: "账号",
                      focusNode: accountFocusNode,
                      controller: accountTextEditingController,
                      decoration: const BoxDecoration(border: null),
                      clearButtonMode: OverlayVisibilityMode.editing,
                    ),
                  ),
                ),
              ),
              const SizedBox(
                width: double.infinity,
                height: 20,
              ),
              CupertinoApp(
                debugShowCheckedModeBanner: false,
                home: Container(
                  color: Colors.white,
                  child: Container(
                    padding: const EdgeInsets.all(5),
                    decoration: BoxDecoration(
                        border: passwordErrStatus
                            ? const Border.fromBorderSide(
                                BorderSide(color: Colors.red))
                            : null,
                        color: const Color.fromRGBO(249, 249, 250, 1),
                        borderRadius:
                            const BorderRadius.all(Radius.circular(10))),
                    child: CupertinoTextField(
                      maxLength: 30,
                      obscureText: true,
                      placeholder: "密码",
                      focusNode: passwordFocusNode,
                      controller: passwordTextEditingController,
                      decoration: const BoxDecoration(border: null),
                      clearButtonMode: OverlayVisibilityMode.editing,
                      onChanged: (password) {},
                    ),
                  ),
                ),
              ),
              const SizedBox(
                width: double.infinity,
                height: 20,
              ),
              Container(
                alignment: Alignment.centerRight,
                child: Text(
                  warningMsg,
                  style: const TextStyle(fontSize: 12, color: Colors.red),
                ),
              ),
              const SizedBox(
                width: double.infinity,
                height: 20,
              ),
              ElevatedButton(
                  onPressed: () async {
                    String account = accountTextEditingController.text;
                    String password = passwordTextEditingController.text;
                    logger.i("account: $account, password: $password");
                    if (StringUtils.isEmpty(account)) {
                      logger.i("账号不允许为空");
                      setWarningMsg("账号不允许为空", true, false);
                      FocusScope.of(context).requestFocus(accountFocusNode);
                      return;
                    }
                    if (StringUtils.isEmpty(password)) {
                      logger.i("密码不允许为空");
                      setWarningMsg("请输入密码", false, true);
                      FocusScope.of(context).requestFocus(passwordFocusNode);
                      return;
                    }
                    Result result = await TokenUtils.login(account, password);
                    if (result.code == 0) {
                      await appUserDetailChangeNotifier.reload();
                      RouteUtils.route2MobileHomePageAndCleanStack();
                    } else {
                      setWarningMsg("账号或密码错误", false, false);
                    }
                  },
                  child: Container(
                    alignment: Alignment.center,
                    width: double.infinity,
                    height: 50,
                    child: const Text(
                      "登录",
                      style: TextStyle(fontSize: 22, color: Colors.black),
                    ),
                  )),
              Row(
                mainAxisAlignment: MainAxisAlignment.end,
                children: [
                  Container(
                    padding: const EdgeInsets.only(top: 10, right: 30),
                    child: const Text(
                      "忘记密码",
                      style: TextStyle(
                          color: Colors.blue,
                          decoration: TextDecoration.underline,
                          decorationColor: Colors.blue,
                          fontSize: 16),
                    ),
                  ),
                  Container(
                    padding: const EdgeInsets.only(top: 10, right: 30),
                    child: TextButton(
                        onPressed: () {
                          RouteUtils.route2MobileRegisterPage();
                        },
                        child: const Text(
                          "注册账户",
                          style: TextStyle(
                              color: Colors.blue,
                              decoration: TextDecoration.underline,
                              decorationColor: Colors.blue,
                              fontSize: 16),
                        )),
                  )
                ],
              )
            ],
          ),
        ),
      ));
    });
  }
}
